package com.example.springsecurity.common.filter.handle;

import cn.hutool.json.JSONUtil;
import com.example.springsecurity.common.resp.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.example.springsecurity.common.enums.GlobalExceptionEnum.ERROR_SERVER_USER_AUTH_FAIL;

/**
 * @Description：当未登录或者token失效访问接口时，自定义的返回结果
 * @Author：fengcheng
 * @Date：2025/1/17 10:51
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(ResponseResult.unauthorized(ERROR_SERVER_USER_AUTH_FAIL.getMessage())));
        response.getWriter().flush();
    }
}
